<?php

namespace IDock\Insurance\TPBX;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\AMIC\Request\AllAMICRequest;
use IDock\Insurance\AMIC\Response\AllAMICResponse;
use IDock\Insurance\TPBX\Request\AllTPBXRequest;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return  $this->config;
    }

    protected $ip;

    protected $config;

    protected $appId;

    protected $appKey;
    protected $channelName;

    protected $notifyUrl;

    protected $fileGateway;

    public function execute(Request $request): Response
    {
        /*** @var AllTPBXRequest $request */
        $request->loadConfig($this->config);
        $request->setRequestId(md5(uniqid()));
        $request->setHeaders(['Content-Type' => 'application/json']);
        if($request->requestType == 'V906'){
            $request->url = $this->notifyUrl;
        }
        $data = $this->generate($request);
        $request->setConfig();
        $header = [
            'requestType' => $request->requestType,
            'password' => $request->password,
            'account' => $request->account,
        ];

        $param = [
            'head' => $header,
        ];

        if ($data) {
            $param['requestInfo'] = $data;
        }

        $request->setPreParameter($param);
        $request->setBizParam(json_encode($param,320));
        if($request->requestType == 'file'){
            $url = $this->fileGateway.'?user='.$header['account'].'&password='.urlencode($header['password']);
            $fileUrl = $data['url'] ?? '';
            unset($data['url']);
            $request->setGateway($url);
            $request->setHeaders($data);
            $request->setPreParameter('');
            $request->setBizParam(file_get_contents($fileUrl));
        }
        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }


    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /**
         * @var AllAMICResponse $response
         */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if($response->isSuccess()){
            $response->printerInit();
        }
        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     */
    public function encrypt(Request $request)
    {

    }
}


